---
- name: Install iptables packages
  yum:
    name: "{{ item }}"
    state: present
  with_items:
  - iptables
  - iptables-services
  register: install_result

- name: Check if firewalld is installed
  command: rpm -q firewalld
  register: pkg_check
  failed_when: pkg_check.rc > 1
  changed_when: no

- name: Ensure firewalld service is not enabled
  service:
    name: firewalld
    state: stopped
    enabled: no
  when: pkg_check.rc == 0

- name: Reload systemd units
  command: systemctl daemon-reload
  when: install_result | changed

- name: Start and enable iptables service
  service:
    name: iptables
    state: started
    enabled: yes
  register: result

- name: need to pause here, otherwise the iptables service starting can sometimes cause ssh to fail
  pause: seconds=10
  when: result | changed

# TODO: submit PR upstream to add mask/unmask to service module
- name: Mask firewalld service
  command: systemctl mask firewalld
  register: result
  changed_when: "'firewalld' in result.stdout"
  when: pkg_check.rc == 0
  ignore_errors: yes

- name: Add iptables allow rules
  os_firewall_manage_iptables:
    name: "{{ item.service }}"
    action: add
    protocol: "{{ item.port.split('/')[1] }}"
    port: "{{ item.port.split('/')[0] }}"
  with_items: os_firewall_allow
  when: os_firewall_allow is defined

- name: Remove iptables rules
  os_firewall_manage_iptables:
    name: "{{ item.service }}"
    action: remove
    protocol: "{{ item.port.split('/')[1] }}"
    port: "{{ item.port.split('/')[0] }}"
  with_items: os_firewall_deny
  when: os_firewall_deny is defined
